package com.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.common.R;
import com.springboot.pojo.Category;
import com.springboot.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
     private CategoryService categoryService;

     @PostMapping
    public R<String> addCategory(@RequestBody Category category){
         categoryService.save(category);
         log.info("新增分类：{}",category);
         return R.success("新增分类成功");
     }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
     @GetMapping("/page")
     public  R<Page> queryCategory(int page, int pageSize){
         //分页
           Page<Category> pagequery = new Page<>(page,pageSize);
           //查询条件
         LambdaQueryWrapper<Category> wrapper =new LambdaQueryWrapper<>();
         //根据升序排序
         wrapper.orderByAsc(Category::getSort);
         categoryService.page(pagequery,wrapper);
         return R.success(pagequery);
     }
     /**
      * 根据id删除
      * @param ids
      * @return
      */
     @DeleteMapping
    public  R<String> deleteCategory(Long ids){
         log.info("删除分类：{}",ids);
       // categoryService.removeById(ids);
         categoryService.remaveCategory(ids);
         return R.success("删除分类成功");
     }

    /**
     * 修改菜品分类
     * @param category
     * @return
     */
    @PutMapping
     public  R<String> updateCategory( @RequestBody  Category category){
        log.info("更新分类：{}",category);
         categoryService.updateById(category);
         return R.success("更新分类成功");
     }

    /**
     * 根据条件（type）查询分类数据
     * @param category
     * @return
     */
     @GetMapping("/list")
     public R<List<Category>> list( Category category){
         System.out.println("查询分类数据："+category);
         //条件构造器
         LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
         //添加条件
         wrapper.eq(category.getType()!=null,Category::getType,category.getType());
         //添加排序条件
         wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
         List<Category> list = categoryService.list(wrapper);
         return R.success(list);
     }
}
